import React from 'react';
import Affix from './Affix';
import ReactDom from 'react-dom'
export  default function(Elem){
    return class Doc extends React.Component{
        constructor(props){
            super(props);
            this.state={
                menus:[],
                active:0
            }
        }
        componentDidMount(){
            let scrollToTop = window.setInterval(function() {
                let pos = window.pageYOffset;
                if ( pos > 0 ) {
                    window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
                } else {
                    window.clearInterval( scrollToTop );
                }
            }, 2);
            this.element =  $(ReactDom.findDOMNode(this));
            // $("img").lazyload({threshold:200,container:this.element});
            this.Node = ReactDom.findDOMNode(this);
            const menus =this.element.find('[data-name]');
            let arr =[];
            $.each(menus,(key,val)=>{
                let data = $(val).data();
                data.position  ={};
                data.position.start = parseInt($(val).position().top);
                if(key==menus.length-1){
                    data.position.end = $(document).height();
                }
                else{
                    data.position.end = parseInt($(menus[key+1]).position().top)
                }
                arr.push(data);
            })
            this.setState({
                menus:arr,
                active:0
            })
            // this.props.changeMenus(arr);
            window.addEventListener('scroll', this.handleScroll);

        }
        componentWillUnmount(){
            window.removeEventListener('scroll', this.handleScroll)
        }
        handleScroll=()=>{
            const {menus} = this.state;
            const current= parseInt($(window).scrollTop());
            $.each(menus,(key,item)=>{
                if((current>item.position.start && current<item.position.end)){
                    this.setState({
                        active:key
                    })
                    return false;
                }
            })
        }
        changeActive=(key,name)=>{
            this.setState({
                active:key
            })
            let top = this.element.find('[data-name="' + name + '"]').offset().top;
            $(window).scrollTop(top-60);
        }
        render(){
            return(
                <React.Fragment>
                    <div className="separator" style={{width:'800px',marginTop:'20px'}}>
                    <Elem/>
                    </div>
                    <Affix menus={this.state.menus} active={this.state.active} changeActive={this.changeActive}/>
                </React.Fragment>
             )
        }
    }
}
